//
//  XHF_RegSeccodeViewController.m
//  haojia
//
//  Created by 徐宏飞 on 16/5/4.
//  Copyright © 2016年 徐宏飞. All rights reserved.
//

#import "XHF_RegSeccodeViewController.h"
#import "XHF_LoginViewController.h"
#import "PerfectInfoViewController.h"  //个人信息完善


@interface XHF_RegSeccodeViewController ()<NetworkToolerDelegate, UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;      //下一步

@property (weak, nonatomic) IBOutlet UITextField *tfdUerName;//手机号输入框
@property (weak, nonatomic) IBOutlet UITextField *tfdPwd;    //密码
@property (weak, nonatomic) IBOutlet UITextField *tfdCopyPwd;//重复
@property (weak, nonatomic) IBOutlet UITextField *tfdsms;    //y验证码输入框
@property (weak, nonatomic) IBOutlet UIButton *rightBtn;


@property (nonatomic, strong) UIImageView *imgUserName;
@property (nonatomic, strong) UIImageView *imgPwd;
@property (nonatomic, strong) UIImageView *imgCopyPwd;
@property (nonatomic, strong) UIImageView *imgSms;


@property (weak, nonatomic) IBOutlet UIScrollView *scrollV;
@property (weak, nonatomic) IBOutlet UIView *baseView;

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger timeNumber;

@property (nonatomic, strong) UITapGestureRecognizer *tap;

@property (nonatomic, strong) NSString *sms;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imgIconTop;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imgIconButtom;


@property (strong, nonatomic)NetworkTooler *networkTool;

@end

@implementation XHF_RegSeccodeViewController




#pragma mark - life cycle

- (void)initNavigationBar
{
    self.enableReturnButton = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = UIColorFromRGB(0xFAFAFA);
    
    
    //用户
    self.tfdUerName.leftView = self.imgUserName;
    self.tfdUerName.leftViewMode = UITextFieldViewModeAlways;
    
    //密码
    self.tfdPwd.leftView = self.imgPwd;
    self.tfdPwd.leftViewMode = UITextFieldViewModeAlways;
    
    //重复密码
    self.tfdCopyPwd.leftView = self.imgCopyPwd;
    self.tfdCopyPwd.leftViewMode = UITextFieldViewModeAlways;
    
    
    //验证码
    self.tfdsms.leftView = self.imgSms;
    self.tfdsms.leftViewMode = UITextFieldViewModeAlways;
    
//    self.tfdsms.rightView = self.rightBtn;
//    self.tfdsms.rightViewMode = UITextFieldViewModeAlways;
    
    [_baseView addGestureRecognizer:self.tap];
    
    
    
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.scrollV.scrollEnabled = NO;
    
    switch (self.smsType) {
            
        case SMSTYP_WORK_REGISTRT:
            [self.nextBtn setTitle:@"注册" forState:UIControlStateNormal];
            
            break;
        case SMSTYP_WORK_EFORGET:
            [self.nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
            
            break;
            
            
            
        default:
            break;
    }
    
    
    if (SCREEN_HEIGHT == 480) {
        self.imgIconTop.constant = 15;
        self.imgIconButtom.constant = 20;
    }
    
    
    
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    //监听键盘的弹出事件
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    [center addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    
    //初始化计时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(trackAction) userInfo:nil repeats:YES];
    [self.timer setFireDate:[NSDate distantFuture]]; //关闭
    
    
}



- (void)viewDidDisappear:(BOOL)animated{
    //移除监听
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



#pragma mark - data

-(void) _testRequst{
    
    
    NSDictionary *parameters = @{
                                 
                                 @"mobile":self.tfdUerName.text,
                                 @"type":@(self.smsType)
                                 
                                 };
    if (!_networkTool) {
        _networkTool = [NetworkTooler new];
    }
    _networkTool.delegate = self;
    [_networkTool parameters:parameters withURL:GetMsgCode_show withIsPaparameters:YES];

    
}

-(void) _RegisterRequst{  //注册
    
    NSString *md5 = [CJMD5 md5HexDigest:self.tfdPwd.text];

    NSDictionary *parameters = @{
                                 
                                 @"mobile":self.tfdUerName.text,
                                 @"password":md5,
                                 @"msg_code":self.tfdsms.text
                                 
                                 };
    _networkTool.delegate = self;
    [_networkTool parameters:parameters withURL:Register_show withIsPaparameters:YES];
}


- (void) _forgetRequst{    //修改密码
    
    NSString *md5 = [CJMD5 md5HexDigest:self.tfdPwd.text];

    NSDictionary *parameters = @{
                                 
                                 @"mobile":self.tfdUerName.text,
                                 @"resetPassword":md5,
                                 @"msg_code":self.tfdsms.text
                                 
                                 };
    _networkTool.delegate = self;
    [_networkTool parameters:parameters withURL:ResetPassword_show withIsPaparameters:YES];

}

#pragma mark - NetworkToolerDelegate

- (void)returnData:(id)data{
    
    if ([data integerValue]>0) {
        return;
    }
    //将数据写入本地
    
    [[NSUserDefaults standardUserDefaults] setObject:self.self.tfdUerName.text forKey:@"mobile"];
    
    
    //同步数据
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [self actionAlert];
    
    
}
- (void)returnRequestError:(NSError *)error{
    
    
}
- (void)returnMsg:(NSString *)Msg{
    //失败
    [self showAlertWithTitle:@"温馨提示" message:Msg cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
    
    
    if ([Msg isEqualToString:@"该手机号已经注册"]) {
        [self.timer setFireDate:[NSDate distantFuture]]; //关闭
        _rightBtn.enabled = YES;
    }
    if ([Msg isEqualToString:@"该手机号未注册"]) {
        [self.timer setFireDate:[NSDate distantFuture]]; //关闭
        _rightBtn.enabled = YES;
    }
}








#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    return YES;
}


#pragma mark - private methods
- (void)actionAlert{
    [self.view endEditing:YES];
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示!" message:@"操作成功" preferredStyle:UIAlertControllerStyleAlert];
    
    [self presentViewController:alertC animated:YES completion:^{
        NSLog(@"页面跳转完成");
    }];
    
    //添加一个确定按钮
    UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
       [self.navigationController popViewControllerAnimated:YES];
        
    }];
    //添加提示按钮
    [alertC addAction:alertA];
}

- (void)nextActionAlert{
    [self.view endEditing:YES];
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"注册成功!" message:@"是否去完善信息" preferredStyle:UIAlertControllerStyleAlert];
    
    [self presentViewController:alertC animated:YES completion:^{
        NSLog(@"页面跳转完成");
    }];
    
    //添加一个确定按钮
    UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"现在就去" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //进入信息完善页面
        PerfectInfoViewController *perfect = [PerfectInfoViewController new];
        [self.navigationController pushViewController:perfect animated:YES];
        
    }];
    
    //添加一个确定按钮
    UIAlertAction *alertB = [UIAlertAction actionWithTitle:@"先不" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        //返回
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    
    
    //添加提示按钮
    [alertC addAction:alertA];
    [alertC addAction:alertB];
}





#pragma mark - event response

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (void)TapAction{
    [self.view endEditing:YES];
}

- (void)keyboardWillChangeFrame:(NSNotification *)notification{
    //获取键盘的Y值
    CGRect rect = [[notification.userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    CGFloat keybordY = rect.origin.y;
    //    NSLog(@"yyy%lf", keybordY);
    CGFloat tranformValue = keybordY - self.view.frame.size.height;
    CGFloat value = 0.4;
    if (SCREEN_HEIGHT == 568) {
        value = 1;
    }
    
    if (SCREEN_HEIGHT == 480) {
        value = 1;
    }
    
    if (tranformValue >= 0) {
        tranformValue = 0;
    }
    
    CGPoint point = CGPointMake(0, -tranformValue*value);
    _scrollV.contentOffset = point;
 
}

- (void)trackAction{
    _timeNumber ++;
    [_rightBtn setTitle:[NSString stringWithFormat:@"%ld", 10 - _timeNumber] forState:UIControlStateDisabled];
    if (_timeNumber >= 10) {
        [self.timer setFireDate:[NSDate distantFuture]]; //关闭
        _rightBtn.enabled = YES;
        
    }
    
    
}


- (IBAction)rightBtnAction:(id)sender {
    //过滤登录条件
    if ([self.tfdUerName.text isEqualToString:@""]) {
        [self showAlertWithTitle:@"温馨提示" message:@"手机号不能为空" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return;
    }
    
    if (![self numIsvalid:self.tfdUerName.text]) {
        [self showAlertWithTitle:@"温馨提示" message:@"手机号码不合法" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return;
    }
    
    
    //倒计时
    _rightBtn.enabled = NO;
    _timeNumber = 0;
    [self.timer setFireDate:[NSDate distantPast]];   //开启
    
    //获取验证码
    [self _testRequst];
}




- (IBAction)nextBtnClick:(id)sender {
    //过滤登录条件
    if ([self.tfdUerName.text isEqualToString:@""]) {
        [self showAlertWithTitle:@"温馨提示" message:@"账户不能为空" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return;
    }
    
    if (![self PhoneNumIsvalid:self.tfdUerName.text]) {
        [self showAlertWithTitle:@"温馨提示" message:@"账号不合法" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return;
    }
    
    
    if ([self.tfdPwd.text isEqualToString:@""]) {
        [self showAlertWithTitle:@"温馨提示" message:@"密码不能为空" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return;
    }
    
    if (![self passWordCodeIsvalid:self.tfdPwd.text]) {
        [self showAlertWithTitle:@"密码不合法" message:@"密码只能由6-20位的数字和大小写的字母组成" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return;
    }
    
    
    
    
    if (![self.tfdPwd.text isEqualToString:self.tfdCopyPwd.text]) {
        [self showAlertWithTitle:@"温馨提示" message:@"密码两次输入不相同" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return;
    }
    
    if ([self.tfdsms.text isEqualToString:@""]) {
        [self showAlertWithTitle:@"温馨提示" message:@"验证码不能为空" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return;
    }
    
    
    
    
    switch (self.smsType) {
            
        case SMSTYP_WORK_REGISTRT:
            [self _RegisterRequst];  //注册
            
            break;
        case SMSTYP_WORK_EFORGET:    //重置密码
            [self _forgetRequst];
            
            break;
            
            
            
        default:
            break;
    }
    
  
}





- (BOOL)numIsvalid:(NSString *)num{
    
    NSString *regex = @"^[1][3578][0-9]{9}$";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [pred evaluateWithObject:num];
    
}


#pragma mark - gettsers and setters
- (UIView *)imgUserName{
    if (!_imgUserName) {
        _imgUserName = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"userIcon"]];
        _imgUserName.frame = CGRectMake(0, 0, 20, 20);
    }
    
    return _imgUserName;
}

- (UIView *)imgPwd{
    if (!_imgPwd) {
        _imgPwd = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pwdIcon"]];
        _imgPwd.frame = CGRectMake(0, 0, 20, 20);
    }
    return _imgPwd;
}

- (UIView *)imgCopyPwd{
    if (!_imgCopyPwd) {
        _imgCopyPwd = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pwdIcon"]];
        _imgCopyPwd.frame = CGRectMake(0, 0, 20, 20);
    }
    return _imgCopyPwd;
}


- (UIView *)imgSms{
    if (!_imgSms) {
        _imgSms = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pwdIcon"]];
        _imgSms.frame = CGRectMake(0, 0, 20, 20);
    }
    return _imgSms;
}




- (UITapGestureRecognizer *)tap{
    if (!_tap) {
        _tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(TapAction)];
    }
    return _tap;
}


@end
